$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'sys/sysactiveinfo/list',
        datatype: "json",
        colModel: [			
			{ label: '活动id', name: 'activeInfoId', index: "activeId", width: 45, key: true },
			{ label: '活动名称', name: 'sysActive.title', width: 75 },
			{ label: '活动类型', name: 'sysActive.type', width: 60,formatter:function(value,options,row){
			        return value==1?'天天奖励':value==2?'周期奖励':'新手奖励';
                } },
            { label: '合伙人要求（位）', name: 'subNum', width: 45,formatter:function(value,options,row){
                    return value+"位";
                }},
			{ label: '激活要求（台）', name: 'activityNum', width: 75,formatter:function(value,options,row){
                    return value+"台";
                }},

            { label: '购买要求（台）', name: 'buyNum', width: 60,formatter:function(value,options,row){
                    if(value == null){
                        $("#jqGrid").setGridParam().hideCol("realBuyNum");
                        //这个就是通过判断这个是否有值显示或者隐藏
                    }else{
                        $("#jqGrid").setGridParam().showCol("realBuyNum");
                        return value + '台';
                    }

                }},
			{ label: '开始时间', name: 'startDate', width: 75},
            { label: '结束时间', name: 'endDate', width: 75},
            { label: 'vip等级', name: 'level', width: 75,formatter:function(value,options,row){
                    return "V"+value;
                }},
            { label: '达标奖励（元）', name: 'money', width: 75,formatter:function(value,options,row){
                    return value+"元";
                }},
            { label: '是否删除', name: 'sysActive.isDel',  width: 75,formatter:function(value,options,row){
                return value==1?'进行中':'已删除';
                }},

            { label: '操作',name:'activeInfoId',formatter:function(value, options, row){
                    return   '<span class = "btn btn-success" onclick = "detail('+value+')"> 详情 </span>&nbsp;&nbsp;'+
                        '<span class = "btn btn-success" onclick = "toUpdate('+value+')"> 修改 </span>&nbsp;&nbsp;'+
                        '<span class="btn btn-danger" onclick="delActiveInfo('+value+')">删除</span>&nbsp;&nbsp;';

                }}

        ],
		viewrecords: true,
        height: 385,
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });

    BindType();
    BindVip();

});

$(function () {
    $("#type").change(function () {
        vm.q.activeId=$(this).val();
    });
    $("#level").change(function () {
        vm.q.level=$(this).val();
    });
    $("#addType").change(function () {
        if($(this).val()==2){
            vm.showCycle=true;
        }else {
            vm.showCycle=false;
        }
    })
});


function delActiveInfo(id){
    var activeInfoId=id;
    confirm("确定要删除选中该活动？",function(){
        $.ajax({
            type: "POST",
            url: baseURL + "sys/sysactiveinfo/deleteById",
            dataType: "json",
            data: {"activeInfoId":activeInfoId},
            success: function(r){
                if(r.code == 0){
                    alert('操作成功', function(){
                        vm.reload();
                    });
                }else{
                    alert(r.msg);
                }
            }
        });

    });
}

function detailAgent(aid){

    $.ajax({
        type: "POST",
        url: baseURL + "sys/sysagent/findDetailById",
        dataType: "json",
        data: {"agentId":aid},
        success: function(r){
            vm.title="查看详情";
            vm.showList=false;
            vm.showUpdate=false;
            vm.showDetail=true;
            vm.agent=r.agent;
            vm.agent.thisGrade= vm.agent.thisGrade==null?'无等级':vm.agent.thisGrade;
        }
    });
}

function toUpdate(aid){
    $.ajax({
        type: "POST",
        url: baseURL + "sys/sysactiveinfo/findInfoById",
        dataType: "json",
        data: {"activeInfoId":aid},
        success: function(r){
            console.log(r);
            if(r.code == 0){
                vm.bindData();
                BindDate();
                vm.showList = false;
                vm.showAdd=true;
                vm.showUpdate=false;
                if(r.activeInfo.buyNum ==null){
                    vm.showCycle=false;
                }else {
                    vm.showCycle=true;
                }
                vm.activeInfo=r.activeInfo;
                //绑定下拉框

                $("#instart").val(vm.activeInfo.startDate);
                $("#inend").val(vm.activeInfo.endDate);
            }else{
                alert(r.msg)

            }

        }
    });
}

var vm = new Vue({
    el:'#rrapp',
    data:{
        q:{
            activeId: null,
            level:null,
            startDate:null,
            endDate:null
        },
        showList: true,
        showAdd:false,
        showCycle:false,
        showUpdate:false,
        title:null,
        activeInfo:{
            activeId:null,
            vipNum:null,
            activityNum:null,
            buyNum:null,
            level:null,
            money:null,
            remark:null,
            startDate:null,
            endDate:null
        },
        active:{
            title:null,
            type:null,
            is_del:null
        }
    },
    methods: {
        query: function () {
            vm.reload();
        },
        clean:function(){
            vm.showList = true;
            vm.showCycle=false;
            $("#jqGrid").jqGrid('setGridParam',{
                postData:{'activeId': null,'level':null,'startDate':null,"endDate":null},
                page:1
            }).trigger("reloadGrid");
        },
        add: function(){
            vm.showList = false;
            vm.showAdd=true;
            vm.showUpdate=false;
            vm.title = "新增";
            vm.activeInfo={
                activeId:null,
                vipNum:null,
                activityNum:null,
                buyNum:null,
                level:null,
                money:null,
                remark:null,
                startDate:null,
                endDate:null
            };
            //绑定下拉框
            this.bindData();
            BindDate();
        },
        insert:function(){


            vm.activeInfo.startDate=$("#instart").val();
            vm.activeInfo.endDate=$("#inend").val();
            $.ajax({
                url: baseURL + "sys/sysactiveinfo/add",
                type: "post",
                contentType: "application/json",
                data: JSON.stringify(vm.activeInfo),
                success: function (r) {
                    if(r.code === 0){
                        alert('操作成功', function(){
                            vm.reload();
                        });
                    }else{
                        alert(r.msg);
                    }
                }
            })
        },


        update: function () {
            vm.activeInfo.startDate=$("#instart").val();
            vm.activeInfo.endDate=$("#inend").val();
            $.ajax({
                url: baseURL + "sys/sysactiveinfo/update",
                type: "post",
                contentType: "application/json",
                data: JSON.stringify(vm.activeInfo),
                success: function (r) {
                    if(r.code === 0){
                        alert('操作成功', function(){
                            vm.reload();
                        });
                    }else{
                        alert(r.msg);
                    }
                }
            })
        },
        bindData:function(){
            $.getJSON(baseURL + "sys/sysactive/list", (result)=>{
                var text="";
                var list=result.page;
                for (var i=0;i<list.length;i++){
                    text+="<option value="+list[i].activeId+">"+list[i].title+"</option>";
                }
                $("#addType").append(text);
            });
            $.getJSON(baseURL + "sys/syslevelrate/list", (result)=>{
                var  text="";
                var list=result.page;
                for (var i=0;i<list.length;i++){
                    text+="<option value="+list[i].lvId+">"+"V"+list[i].lv+"</option>";
                }
                $("#addLevel").append(text);
            });
        },

        reload: function () {
            vm.showList = true;
            vm.showCycle=false;
            vm.showUpdate=false;
            vm.showAdd=false;
            vm.q.startDate=$("#startTime").val();
            vm.q.endDate=$("#endTime").val();
            if(vm.q.startDate==''){
                vm.q.startDate=null;
            }
            if(vm.q.endDate==''){
                vm.q.endDate=null;
            }
            $("#jqGrid").jqGrid('setGridParam',{
                postData:{'activeId': vm.q.activeId,'level':vm.q.level,'startDate':vm.q.startDate,"endDate":vm.q.endDate},
                page:1
            }).trigger("reloadGrid");
        },
    }
});


        function BindType(){
            $.getJSON(baseURL + "sys/sysactive/list", (result)=>{
                var text="";
                var list=result.page;
                for (var i=0;i<list.length;i++){
                    text+="<option value="+list[i].activeId+">"+list[i].title+"</option>";
                }
                $("#type").append(text);
            });

        }


        function BindVip(){
            $.getJSON(baseURL + "sys/syslevelrate/list", (result)=>{
                var  text="";
                var list=result.page;
                for (var i=0;i<list.length;i++){
                    text+="<option value="+list[i].lvId+">"+"V"+list[i].lv+"</option>";
                }
                $("#level").append(text);
            });

        }

        function BindDate(){
            var start = {}, end = {};
            start.maxDate=$("#inend").val();
            end.minDate=$("#instart").val();
            jeDate('#instart',{

                format: 'YYYY-MM-DD hh:mm:ss',
                minDate: '2014-06-16 23:59:59', //设定最小日期为当前日期
                maxDate: function (that) {
                    //that 指向实例对象
                    return jeDate.valText(that.valCell) == "" ? jeDate.nowDate({DD:0}) : start.maxDate;
                }, //设定最大日期为当前日期
                donefun: function(obj){
                    end.minDate = obj.val; //开始日选好后，重置结束日的最小日期
                    jeDate("#inend",LinkageEndDate(false));
                }
            });
            jeDate('#inend',LinkageEndDate);

            function LinkageEndDate(istg) {
                return {
                    trigger : istg,
                    format: 'YYYY-MM-DD hh:mm:ss',
                    minDate: function (that) {
                        //that 指向实例对象
                        var nowMinDate = jeDate.valText('#instart') == "" && jeDate.valText(that.valCell) == "";
                        return nowMinDate ? jeDate.nowDate({DD:0}) : end.minDate ;
                    }, //设定最小日期为当前日期
                    maxDate: '2099-06-16 23:59:59', //设定最大日期为当前日期
                    donefun: function(obj){
                        start.maxDate = obj.val; //将结束日的初始值设定为开始日的最大日期
                    }
                };
            }
        }